<?php


namespace App\Services\Game;

use App\DTOS\Admin\LogRoleStallDTO;
use App\DTOS\Admin\UserMemberDTO;
use App\Exceptions\ServiceException;
use App\Models\Game\Equip;
use App\Models\Game\LogRoleStall;

class LogRoleStallService
{

    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    /**
     * LogRoleStallService constructor.
     * @param UserRoleService $userRoleService
     * @param UserMemberService $userMemberService
     */
    public function __construct(UserRoleService $userRoleService, UserMemberService $userMemberService)
    {
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }

    public function paginate(LogRoleStallDTO $DTO){

        $model = LogRoleStall::query();
        $perPage = $DTO->getLimit();
        $page = $DTO->getPage();
        global $gameArea; //选择分区
        $gameArea = $DTO->getGameArea(); //赋值
        $memberName = $DTO->getMemberName();
        $roleName = $DTO->getRoleName();
        $roleId = $DTO->getRoleId();
        $equipName = $DTO->getEquipName();
        $equipId = $DTO->getEquipId();
        $uuid = $DTO->getUuid();
        $createTimeBegin = $DTO->getCreateTimeBegin();
        $createTimeEnd = $DTO->getCreateTimeEnd();
        if ($memberName){
            $userMemberPaginate = $this->userMemberService->paginate(new UserMemberDTO(['username'=>$memberName]));
            $searchMems = $userMemberPaginate->items();
            $searchMemIds = collect($searchMems)->pluck('id')->unique()->toArray();
            if (empty($searchMemIds)){
                throw new ServiceException("此账号不存在");
            }
            $model->whereIn('memId',$searchMemIds);
        }
        if ($roleName){
            $model->where('nick','like',"%$roleName%");
        }
        if ($roleId){
            $model->where('roleId',$roleId);
        }
        if ($equipName){
            $equipIds = Equip::query()->where('name','like',"%$equipName%")->pluck('id')->toArray();
            $model->whereIn('item_id',$equipIds);
        }
        if ($equipId){
            $model->where('item_id',$equipId);
        }
        if ($uuid){
            $model->where('unique_id',$uuid);
        }
        if ($createTimeBegin){
            $model->where('logTime','>=',strtotime($createTimeBegin));
        }
        if ($createTimeEnd){
            $model->where('logTime','<=',strtotime($createTimeEnd));
        }
        return $model->orderByDesc('logTime')->paginate($perPage,'*','page',$page);
    }
}
